#!/usr/local/python3/bin/python3

# -*- coding:utf8 -*-
import threading, time, sys, os, logging, random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


def run(n):
    logging.warning("chrome开始运行")
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    ## selenium 低版本【python 3.7】
    # browser = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=chrome_options)
    ## selenium 高版本【python 3.9】
    service = Service('/usr/bin/chromedriver')
    browser = webdriver.Chrome(service=service, options=chrome_options)

    # 判断是否包含http
    path = sys.argv[1]
    if path.find("://") != -1:
        browser.get(path)
    else:
        browser.get('file://' + os.path.abspath('html/' + path + '.html'))

    time.sleep(5)
    logging.warning("chrome运行结束")
    browser.quit()


if __name__ == '__main__':
    if len(sys.argv) != 4:
        logging.warning("Usage: python webdriver.py <HTML NAME / URL NAME> <SLEEP TIME> <ENABLE LOG>")
        sys.exit(1)

    logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(filename)s:%(lineno)d] %(message)s',
                    datefmt='# %Y-%m-%d %H:%M:%S')

    if sys.argv[3] != 'true':
        logging.disable(logging.WARNING)

    random_time = random.randint(1, 20)
    logging.warning("随机启动时间" + str(random_time) + "秒")
    time.sleep(random_time)

    while True:
        time.sleep(5)
        logging.warning("进入循环")
        for i in range(20):
            t = threading.Thread(target=run, args=("t-%s" % i,))
            time.sleep(int(sys.argv[2]))
            t.start()

